//
//  LBWUserAccountViewModel.swift
//  weibo
//
//  Created by Limonwei on 15/12/8.
//  Copyright © 2015年 heima. All rights reserved.
//

//抽取用户视图数据模型

import UIKit

class LBWUserAccountViewModel {
    
    //viewModel引用Model
    var userAccount: LBWUserAccount?
    
    //归档与解档的路径
    var archivePath: String = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("useraccount.archive")
    
    //是否登陆
    var userLogin: Bool {
        
        return accessToken != nil
    }
    
    //返回当前用户的accessToken
    var accessToken: String? {
        
        //还得判断是否过期
        if let accessToken = userAccount?.access_token where !isExpires{
            return accessToken
        }
        
        return nil
        
    }
    
    
    //返回true代表过期,false代表没有过期
    var isExpires: Bool {
        guard let expiresDate = userAccount?.expiresDate else{
            return true
        }
        if NSDate().compare(expiresDate) == NSComparisonResult.OrderedAscending {
            return false
        }
        return true
    }
    //全局访问点
    static let shareAccount: LBWUserAccountViewModel = LBWUserAccountViewModel()
    
    //构造方法私有化
    private init(){
        //从归档里接档
        userAccount = loadUserAccount()
        
    }
}


//OAuth 登陆请求
extension LBWUserAccountViewModel {
    
    func loadAccessToken(code: String, complete: (isSuccess: Bool)->()){
        
        LBWNetworkTools.shareTool.loadAccessToken(code) { (response, error) -> () in
            if error != nil {
                
                printLog("请求错误:\(error)")
                
                complete(isSuccess: false)
                
                return
            }
            
            // 在强转的时候,`!` 与 `?` 怎么选,只要看前面的数据是否是一个可选值
            guard let dict = response as? [String: AnyObject] else {
                printLog("返回数据不是字典")
                return
            }
            
            let account = LBWUserAccount(dict: dict)
            
            self.userAccount = account
            
            //请求成功之后删掉此处!!!!!
            //complete(isSuccess: true)
            
            self.loadUserInfo(account.uid!, accessToken: account.access_token!, complete: complete)

        }
        
        
    }
    
    //请求用户数据
    private func loadUserInfo(uid: String, accessToken: String, complete:(isSuccessed: Bool)->()){
        
        LBWNetworkTools.shareTool.loadUserInfo(uid, accessToken: accessToken) { (response, error) -> () in
            if error != nil {
                printLog("请求失败\(error)")
                complete(isSuccessed: false)
                return
            }
            printLog("=================")
            printLog(response)
            
            guard let responseDic = response as? [String: AnyObject] else {
                
                printLog("返回数据不是一个字典")
                return
            }
            
            //赋值用户的头像和昵称
            self.userAccount?.screen_name = responseDic["screen_name"] as? String
            
            self.userAccount?.avatar_large = responseDic["avatar_large"] as? String
            
            //保存
            self.saveAccount(self.userAccount!)
            
            complete(isSuccessed: true)
        }
        
    }
    
    
    
}


//归档与解档当前对象
extension LBWUserAccountViewModel {
    
    //归档当前对象
    func saveAccount(account: LBWUserAccount){
        
        NSKeyedArchiver.archiveRootObject(account, toFile: archivePath)
        
    }
    
    //解档当前对象
    func loadUserAccount() ->LBWUserAccount? {
        
        let result = NSKeyedUnarchiver.unarchiveObjectWithFile(archivePath) as?LBWUserAccount
        
        return result
    }
}
























